package sicket;

import com.sun.media.jfxmediaimpl.HostUtils;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class ClientDemo {
    private Socket socket;

    public ClientDemo(){
        System.out.println("正在连接服务端");
        try {
            socket=new Socket("localhost",8089);
            System.out.println("成功链接服务端");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start(){
        try {
            ServerHandler handler=new ServerHandler();
            Thread t=new Thread(handler);
            t.setDaemon(true);
            t.start();

            Scanner scanner=new Scanner(System.in);
            OutputStream out=socket.getOutputStream();
            OutputStreamWriter osw=new OutputStreamWriter(out, StandardCharsets.UTF_8);
            BufferedWriter bw=new BufferedWriter(osw);
            PrintWriter pw=new PrintWriter(bw,true);
            while (true){
                String str=scanner.next();
                if ("exit".equalsIgnoreCase(str)){
                    break;
                }
                pw.println(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        ClientDemo clientDemo=new ClientDemo();
        clientDemo.start();
    }

    class ServerHandler implements Runnable{
        public void run(){
            try {
                InputStream in=socket.getInputStream();
                InputStreamReader isr=new InputStreamReader(in,StandardCharsets.UTF_8);
                BufferedReader br=new BufferedReader(isr);
                String line;
                while ((line=br.readLine())!=null){
                    System.out.println(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {

                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
